#include "settingswidget.h"
#include "mainwindow.h"
#include "presetmanager.h"
#include "toastnotification.h"
#include "configmanager.h"
#include <QApplication>
#include <QMenu>
#include <QAction>
#include <QRegularExpression>
#include <QMessageBox>
#include <QColorDialog>
#include <QSettings>

SettingsWidget::SettingsWidget(MainWindow* mainWindow, QWidget* parent)
    : QWidget(parent)
    , m_mainWindow(mainWindow)
    , m_changeTimer(new QTimer(this))
{
    // 设置定时器
    m_changeTimer->setSingleShot(true);
    m_changeTimer->setInterval(CHANGE_DELAY_MS);
    connect(m_changeTimer, &QTimer::timeout, this, &SettingsWidget::notifySettingsChanged);

    setupUI();

    // 加载用户保存的默认预设，如果没有则使用"标准文档"
    QString defaultPreset = ConfigManager::getDefaultPreset();
    
    // 验证预设是否存在
    if (!PresetManager::getAllPresetNames().contains(defaultPreset)) {
        defaultPreset = "标准文档"; // 如果预设不存在，回退到默认
    }
    
    m_originalSettings = ProcessingSettings::getPreset(defaultPreset);
    setSettings(m_originalSettings);
    
    // 设置预设下拉框的选中项
    int presetIndex = m_presetCombo->findText(defaultPreset);
    if (presetIndex >= 0) {
        m_presetCombo->setCurrentIndex(presetIndex);
    }
}

SettingsWidget::~SettingsWidget()
{
}

ProcessingSettings SettingsWidget::getSettings() const
{
    return m_currentSettings;
}

void SettingsWidget::setSettings(const ProcessingSettings& settings)
{
    m_originalSettings = settings;
    m_currentSettings = settings;

    // 更新UI控件 - 根据模板名称选择对应的预设
    QString targetPreset = settings.templateName;
    int targetIndex = m_presetCombo->findText(targetPreset);
    if (targetIndex >= 0) {
        m_presetCombo->setCurrentIndex(targetIndex);
    }
    
    // 设置DPI值
    QString dpiText = QString::number(settings.standardDPI);
    m_dpiCombo->setCurrentText(dpiText);
    
    m_autoOptimizeCheck->setChecked(settings.autoOptimizeLargeDocuments);

    // 页边距
    m_topMarginSpin->setValue(settings.margins.top);
    m_bottomMarginSpin->setValue(settings.margins.bottom);
    m_leftMarginSpin->setValue(settings.margins.left);
    m_rightMarginSpin->setValue(settings.margins.right);

    // 页码 - Jony Ive风格设置
    m_pageNumberEnabled->setChecked(settings.pageNumber.enabled);
    m_startNumberSpin->setValue(settings.pageNumber.startNumber);

    // 设置页码格式
    QString format = settings.pageNumber.format;
    QStringList presetFormats = ProcessingSettings::PageNumberSettings::getPresetFormats();
    int formatIndex = presetFormats.indexOf(format);

    if (formatIndex >= 0) {
        m_pageNumberFormatCombo->setCurrentIndex(formatIndex);
        m_pageNumberFormatEdit->clear();
    } else {
        m_pageNumberFormatCombo->setCurrentIndex(-1);
        m_pageNumberFormatEdit->setText(format);
    }

    // === 新增的页码属性设置 ===
    if (m_smartSelector) {
        m_smartSelector->setPageNumberSettings(settings.pageNumber);
    }

    if (m_fontFamilyCombo) {
        m_fontFamilyCombo->setCurrentText(settings.pageNumber.font.family());
    }

    if (m_fontSizeCombo) {
        int fontSize = settings.pageNumber.font.pointSize();
        int fontIndex = m_fontSizeCombo->findData(fontSize);
        if (fontIndex >= 0) {
            m_fontSizeCombo->setCurrentIndex(fontIndex);
        } else {
        }
    }

    if (m_fontBoldButton) {
        m_fontBoldButton->setChecked(settings.pageNumber.font.bold());
    }

    if (m_fontItalicButton) {
        m_fontItalicButton->setChecked(settings.pageNumber.font.italic());
    }

    // 设置页码颜色 - 不再动态改变按钮背景色，保持统一样式
    if (m_fontColorButton) {
        QColor color = settings.pageNumber.color;
        // 移除动态背景色设置，保持与加粗、倾斜按钮一致的样式
    }

    // 精准定位滑块已移除 - 现在使用直接拖拽定位

    // 更新智能选择器预览
    if (m_smartSelector) {
        m_smartSelector->setPageNumberSettings(settings.pageNumber);
    }

    updateContentAreaInfo();
    updateFileEstimate();
    onPageNumberFormatChanged();

    // 更新页码选择器的总页数
    onPageCountChanged();
}

void SettingsWidget::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(4, 4, 4, 4);  // 极紧凑边距适应220px
    m_mainLayout->setSpacing(6);  // 极紧凑间距
    m_mainLayout->setAlignment(Qt::AlignTop); // 顶部对齐

    // 创建滚动区域 - 设置viewport边距为滚动条预留空间
    QScrollArea* scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setFrameShape(QFrame::NoFrame);  // 无边框
    // 通过设置滚动区域边距为滚动条预留空间
    scrollArea->setContentsMargins(0, 0, 20, 0); // 右侧预留20px给滚动条

    // 创建滚动内容容器 - 增加宽度以适应更大的输入框
    QWidget* scrollContent = new QWidget();
    scrollContent->setMaximumWidth(210); // 增加内容宽度为210px
    scrollContent->setFixedWidth(210);   // 固定宽度，为滚动条预留20px
    m_scrollLayout = new QVBoxLayout(scrollContent);
    m_scrollLayout->setContentsMargins(0, 0, 0, 0);
    m_scrollLayout->setSpacing(4);  // 更紧凑滚动内容间距
    m_scrollLayout->setAlignment(Qt::AlignTop);

    // 在滚动布局中添加所有设置组
    setupPresets();
    m_scrollLayout->addWidget(m_presetGroup);

    setupDPIControls();
    m_scrollLayout->addWidget(m_dpiGroup);

    setupMarginControls();
    m_scrollLayout->addWidget(m_marginGroup);

    setupPageNumberControls();
    m_scrollLayout->addWidget(m_pageNumberGroup);

    m_scrollLayout->addStretch(); // 底部拉伸

    // 设置滚动区域的内容
    scrollArea->setWidget(scrollContent);
    m_mainLayout->addWidget(scrollArea);
}

void SettingsWidget::setupPresets()
{
    m_presetGroup = new QGroupBox("预设方案", this);
    QVBoxLayout* presetLayout = new QVBoxLayout(m_presetGroup);
    presetLayout->setContentsMargins(4, 4, 4, 4);  // 极紧凑边距
    presetLayout->setSpacing(4);  // 极紧凑间距
    presetLayout->setAlignment(Qt::AlignTop); // 顶部对齐

    // 预设选择行：下拉框 + 保存按钮（按钮移到最右边）
    QHBoxLayout* presetRowLayout = new QHBoxLayout();
    presetRowLayout->setAlignment(Qt::AlignLeft); // 左对齐
    
    m_presetCombo = new QComboBox(this);
    m_presetCombo->setFixedWidth(130); // 固定宽度，适配200px内容宽度
    updatePresetCombo(); // 使用新的预设更新逻辑
    
    m_savePresetButton = new QPushButton("💾", this);
    m_savePresetButton->setFixedSize(30, 30);
    m_savePresetButton->setToolTip("保存当前设置为选中的预设");
    m_savePresetButton->setEnabled(false); // 默认禁用
    
    presetRowLayout->addWidget(m_presetCombo, 1); // 给下拉框分配更多空间
    presetRowLayout->addSpacing(5); // 缩小间隙
    presetRowLayout->addWidget(m_savePresetButton); // 按钮放在下拉框右边

    presetLayout->addLayout(presetRowLayout);

    connect(m_presetCombo, &QComboBox::currentTextChanged, this, &SettingsWidget::onPresetSelected);
    connect(m_savePresetButton, &QPushButton::clicked, this, &SettingsWidget::saveAsPreset);
    
    // 连接预设下拉框变化信号，控制保存按钮状态
    connect(m_presetCombo, &QComboBox::currentTextChanged, this, [this]() {
        QString currentText = m_presetCombo->currentText();
        bool isUserPreset = PresetManager::isUserPreset(currentText);
        m_savePresetButton->setEnabled(isUserPreset);
    });
}

void SettingsWidget::setupDPIControls()
{
    m_dpiGroup = new QGroupBox("输出质量", this);
    QVBoxLayout* dpiMainLayout = new QVBoxLayout(m_dpiGroup);
    dpiMainLayout->setContentsMargins(4, 4, 4, 4);  // 极紧凑边距
    dpiMainLayout->setSpacing(4);  // 极紧凑间距
    dpiMainLayout->setAlignment(Qt::AlignTop);

    // DPI选择行：标签 + 下拉框
    QHBoxLayout* dpiRowLayout = new QHBoxLayout();
    dpiRowLayout->setAlignment(Qt::AlignLeft);
    dpiRowLayout->setSpacing(10); // 标签和下拉框之间的间距
    
    QLabel* dpiLabel = new QLabel("DPI:", this);
    m_dpiCombo = new QComboBox(this);
    // 使用纯数值DPI选项
    QStringList dpiOptions = {"96", "120", "150", "200", "300", "600"};
    m_dpiCombo->addItems(dpiOptions);
    m_dpiCombo->setEditable(true); // 允许用户输入自定义DPI值
    m_dpiCombo->setFixedWidth(60); // 固定宽度，适配200px内容宽度
    
    dpiRowLayout->addWidget(dpiLabel);
    dpiRowLayout->addWidget(m_dpiCombo);
    dpiRowLayout->addStretch();

    // 自动优化复选框行
    QHBoxLayout* autoOptimizeLayout = new QHBoxLayout();
    autoOptimizeLayout->setAlignment(Qt::AlignLeft);
    m_autoOptimizeCheck = new QCheckBox("大文档优化", this);

    // 创建信息按钮
    QPushButton* infoButton = new QPushButton(this);
    infoButton->setIcon(createInfoIcon());
    infoButton->setMaximumSize(20, 20);
    infoButton->setFlat(true);
    infoButton->setToolTip("当文档超过100页时，自动降低DPI以提高处理速度和减少内存占用");

    autoOptimizeLayout->addWidget(m_autoOptimizeCheck);
    autoOptimizeLayout->addWidget(infoButton);
    autoOptimizeLayout->addStretch();
    
    // 文件大小预估行
    QHBoxLayout* fileSizeLayout = new QHBoxLayout();
    fileSizeLayout->setAlignment(Qt::AlignLeft);
    QLabel* fileSizeLabel = new QLabel("预估文件大小:", this);
    m_fileSizeLabel = new QLabel(this);
    fileSizeLayout->addWidget(fileSizeLabel);
    fileSizeLayout->addWidget(m_fileSizeLabel);
    fileSizeLayout->addStretch();

    dpiMainLayout->addLayout(dpiRowLayout);
    dpiMainLayout->addLayout(autoOptimizeLayout);
    dpiMainLayout->addLayout(fileSizeLayout);

    connect(m_dpiCombo, &QComboBox::currentTextChanged, this, &SettingsWidget::onDPIChanged);
    connect(m_autoOptimizeCheck, &QCheckBox::toggled, this, &SettingsWidget::onSettingsChanged);
}

void SettingsWidget::setupMarginControls()
{
    m_marginGroup = new QGroupBox("页边距(毫米)", this);  // 缩减标题空格
    QVBoxLayout* marginMainLayout = new QVBoxLayout(m_marginGroup);
    marginMainLayout->setContentsMargins(2, 2, 2, 2);  // 更紧凑边距
    marginMainLayout->setSpacing(2);  // 更紧凑间距

    // 使用简单的水平布局替代网格布局
    QWidget* marginWidget = new QWidget();
    marginWidget->setFixedWidth(190); // 增加宽度给输入框
    QHBoxLayout* marginLayout = new QHBoxLayout(marginWidget);
    marginLayout->setContentsMargins(1, 1, 1, 1);  // 最小边距
    marginLayout->setSpacing(2); // 更小间距

    // 创建输入框的通用设置函数
    auto createMarginSpinBox = [this]() {
        QDoubleSpinBox* spinBox = new QDoubleSpinBox(this);
        spinBox->setRange(0, 50);
        spinBox->setSingleStep(1.0);
        spinBox->setDecimals(0); // 不显示小数点
        // 移除mm后缀，因为GroupBox标题已经显示"(毫米)"
        // spinBox->setSuffix(" mm");
        spinBox->setFixedWidth(65); // 增加输入框宽度
        return spinBox;
    };

    m_topMarginSpin = createMarginSpinBox();
    m_bottomMarginSpin = createMarginSpinBox();
    m_leftMarginSpin = createMarginSpinBox();
    m_rightMarginSpin = createMarginSpinBox();

    // 创建标签的通用设置函数 - 缩减标签宽度和文字
    auto createLabel = [](const QString& text) {
        QLabel* label = new QLabel(text);
        label->setFixedWidth(12); // 缩减标签宽度
        label->setAlignment(Qt::AlignCenter);
        return label;
    };

    // 第一行：上、下
    QHBoxLayout* firstRow = new QHBoxLayout();
    firstRow->setSpacing(2);  // 更小间距
    firstRow->addWidget(createLabel("上"));
    firstRow->addWidget(m_topMarginSpin);
    firstRow->addSpacing(5); // 缩减间距
    firstRow->addWidget(createLabel("下"));
    firstRow->addWidget(m_bottomMarginSpin);
    firstRow->addStretch();

    // 第二行：左、右
    QHBoxLayout* secondRow = new QHBoxLayout();
    secondRow->setSpacing(2);  // 更小间距
    secondRow->addWidget(createLabel("左"));
    secondRow->addWidget(m_leftMarginSpin);
    secondRow->addSpacing(5); // 缩减间距
    secondRow->addWidget(createLabel("右"));
    secondRow->addWidget(m_rightMarginSpin);
    secondRow->addStretch();

    // 添加到主布局
    QVBoxLayout* rowsLayout = new QVBoxLayout();
    rowsLayout->setSpacing(1);  // 更小间距
    rowsLayout->addLayout(firstRow);
    rowsLayout->addLayout(secondRow);
    marginLayout->addLayout(rowsLayout);

    marginMainLayout->addWidget(marginWidget);

    // 其他控件
    m_marginPresetButton = new QPushButton("边距预设", this);
    m_contentAreaLabel = new QLabel(this);

    // 内容区域信息布局
    QHBoxLayout* infoLayout = new QHBoxLayout();
    QLabel* infoLabel = new QLabel("内容区域:");
    infoLayout->addWidget(infoLabel);
    infoLayout->addWidget(m_contentAreaLabel, 1);

    marginMainLayout->addWidget(m_marginPresetButton);
    marginMainLayout->addLayout(infoLayout);

    // 连接信号
    connect(m_topMarginSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            this, &SettingsWidget::onMarginChanged);
    connect(m_bottomMarginSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            this, &SettingsWidget::onMarginChanged);
    connect(m_leftMarginSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            this, &SettingsWidget::onMarginChanged);
    connect(m_rightMarginSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            this, &SettingsWidget::onMarginChanged);

    // 连接边距预设按钮
    connect(m_marginPresetButton, &QPushButton::clicked, this, &SettingsWidget::showMarginPresetMenu);
}

void SettingsWidget::setupPageNumberControls()
{
    // Jony Ive风格的一体化页码设置界面
    m_pageNumberGroup = new QGroupBox("页码设计", this);
    QVBoxLayout* pageNumMainLayout = new QVBoxLayout(m_pageNumberGroup);
    pageNumMainLayout->setContentsMargins(3, 3, 3, 3);  // 极紧凑边距适应220px面板
    pageNumMainLayout->setSpacing(4);  // 极紧凑间距

    // 启用复选框（更大更醒目）
    m_pageNumberEnabled = new QCheckBox("启用页码", this);
    m_pageNumberEnabled->setStyleSheet(
        "QCheckBox { font-size: 13px; font-weight: bold; }"
        "QCheckBox::indicator { width: 18px; height: 18px; }"
    );
    pageNumMainLayout->addWidget(m_pageNumberEnabled);

    // === 一体化智能页码选择器 ===
    // 将预览和位置选择完美合并
    m_smartSelector = new SmartPageNumberSelector(this);
    m_smartSelector->setSamplePage(1, 10);
    // 设置尺寸适应200px内容宽度
    m_smartSelector->setFixedSize(180, 150); // 固定尺寸，适配200px内容宽度

    pageNumMainLayout->addWidget(m_smartSelector, 0, Qt::AlignCenter);

    // === 说明文字 ===
    QLabel* instructionLabel = new QLabel("点击页面位置选择\n页码位置", this);
    instructionLabel->setStyleSheet("color: #666; font-size: 10px; padding: 2px;");
    instructionLabel->setAlignment(Qt::AlignCenter);
    instructionLabel->setWordWrap(true);
    pageNumMainLayout->addWidget(instructionLabel);

    // === 快速格式选择 ===
    QGroupBox* formatGroup = new QGroupBox("格式", this);
    QVBoxLayout* formatLayout = new QVBoxLayout(formatGroup);
    formatLayout->setContentsMargins(4, 4, 4, 4);  // 最小边距
    formatLayout->setSpacing(3);  // 最小间距

    m_pageNumberFormatCombo = new QComboBox(this);
    m_pageNumberFormatCombo->setFixedWidth(190); // 增加宽度，适配210px内容宽度
    m_pageNumberFormatCombo->addItems(ProcessingSettings::PageNumberSettings::getPresetFormats());
    m_pageNumberFormatCombo->addItem("自定义...");
    formatLayout->addWidget(m_pageNumberFormatCombo);

    m_pageNumberFormatEdit = new QLineEdit(this);
    m_pageNumberFormatEdit->setFixedWidth(190); // 增加宽度，适配210px内容宽度
    m_pageNumberFormatEdit->setPlaceholderText("自定义格式，如: 第{page}页");
    formatLayout->addWidget(m_pageNumberFormatEdit);

    pageNumMainLayout->addWidget(formatGroup);

    // === 字体设置 ===
    QGroupBox* fontGroup = new QGroupBox("字体", this);
    QVBoxLayout* fontLayout = new QVBoxLayout(fontGroup);
    fontLayout->setContentsMargins(4, 4, 4, 4);  // 最小边距
    fontLayout->setSpacing(4);  // 间距

    // 字体家族
    QHBoxLayout* fontFamilyLayout = new QHBoxLayout();
    fontFamilyLayout->setSpacing(2);  // 最小间距
    QLabel* fontFamilyLabel = new QLabel("字体:", this);
    fontFamilyLabel->setFixedWidth(25); // 缩减标签宽度
    m_fontFamilyCombo = new QComboBox(this);
    m_fontFamilyCombo->setFixedWidth(155); // 增加宽度
    m_fontFamilyCombo->addItems(ProcessingSettings::PageNumberSettings::getPresetFontFamilies());
    fontFamilyLayout->addWidget(fontFamilyLabel);
    fontFamilyLayout->addWidget(m_fontFamilyCombo);
    fontFamilyLayout->addStretch();
    fontLayout->addLayout(fontFamilyLayout);

    // 字号
    QHBoxLayout* fontSizeLayout = new QHBoxLayout();
    fontSizeLayout->setSpacing(2);  // 最小间距
    QLabel* fontSizeLabel = new QLabel("字号:", this);
    fontSizeLabel->setFixedWidth(25); // 缩减标签宽度
    m_fontSizeCombo = new QComboBox(this);
    m_fontSizeCombo->setFixedWidth(70); // 增加字号输入框宽度
    for (int size : ProcessingSettings::PageNumberSettings::getPresetFontSizes()) {
        m_fontSizeCombo->addItem(QString::number(size), size);
    }
    fontSizeLayout->addWidget(fontSizeLabel);
    fontSizeLayout->addWidget(m_fontSizeCombo);
    fontSizeLayout->addStretch();
    fontLayout->addLayout(fontSizeLayout);

    // 字体样式按钮行
    QHBoxLayout* styleLayout = new QHBoxLayout();
    styleLayout->setSpacing(5);  // 按钮间距

    m_fontBoldButton = new QPushButton("B", this);
    m_fontBoldButton->setFixedSize(30, 30);  // 和保存按钮一样大小
    m_fontBoldButton->setCheckable(true);
    m_fontBoldButton->setToolTip("粗体");

    m_fontItalicButton = new QPushButton("I", this);
    m_fontItalicButton->setFixedSize(30, 30);  // 和保存按钮一样大小
    m_fontItalicButton->setCheckable(true);
    m_fontItalicButton->setToolTip("斜体");

    m_fontColorButton = new QPushButton("C", this);
    m_fontColorButton->setFixedSize(30, 30);  // 和保存按钮一样大小
    m_fontColorButton->setToolTip("颜色");

    styleLayout->addWidget(m_fontBoldButton);
    styleLayout->addWidget(m_fontItalicButton);
    styleLayout->addWidget(m_fontColorButton);
    styleLayout->addStretch();
    fontLayout->addLayout(styleLayout);

    pageNumMainLayout->addWidget(fontGroup);

    // === 其他设置 ===
    QHBoxLayout* startLayout = new QHBoxLayout();
    startLayout->setSpacing(2);  // 最小间距
    startLayout->addWidget(new QLabel("起始:"));  // 缩减文字
    m_startNumberSpin = new QSpinBox(this);
    m_startNumberSpin->setRange(1, 9999);
    m_startNumberSpin->setFixedWidth(50); // 增加输入框宽度
    startLayout->addWidget(m_startNumberSpin);
    startLayout->addStretch();
    pageNumMainLayout->addLayout(startLayout);

    // 预览标签
    m_formatPreviewLabel = new QLabel("预览: 1/10", this);
    m_formatPreviewLabel->setStyleSheet("color: #666; font-size: 11px; padding: 4px;");
    pageNumMainLayout->addWidget(m_formatPreviewLabel);

    // === 连接信号 ===
    connect(m_pageNumberEnabled, &QCheckBox::toggled, this, &SettingsWidget::onSettingsChanged);
    connect(m_pageNumberFormatCombo, &QComboBox::currentTextChanged,
            this, &SettingsWidget::onPageNumberFormatChanged);
    connect(m_pageNumberFormatEdit, &QLineEdit::textChanged,
            this, &SettingsWidget::onPageNumberFormatChanged);

    // 一体化智能选择器
    connect(m_smartSelector, &SmartPageNumberSelector::positionChanged,
            this, &SettingsWidget::onSmartPositionChanged);
    connect(m_smartSelector, &SmartPageNumberSelector::settingsChanged,
            this, &SettingsWidget::onSmartSettingsChanged);

    // 字体设置
    connect(m_fontFamilyCombo, &QComboBox::currentTextChanged,
            this, &SettingsWidget::onFontFamilyChanged);
    connect(m_fontSizeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &SettingsWidget::onFontSizeChanged);
    connect(m_fontBoldButton, &QPushButton::toggled,
            this, &SettingsWidget::onFontStyleChanged);
    connect(m_fontItalicButton, &QPushButton::toggled,
            this, &SettingsWidget::onFontStyleChanged);
    connect(m_fontColorButton, &QPushButton::clicked,
            this, &SettingsWidget::onFontColorChanged);

    // 其他设置
    connect(m_startNumberSpin, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &SettingsWidget::onSettingsChanged);
}

void SettingsWidget::onSettingsChanged()
{
    m_changeTimer->start(); // 重启延迟定时器
}

void SettingsWidget::onPresetSelected(const QString& presetName)
{
    if (presetName.isEmpty()) return;
    
    ProcessingSettings presetSettings = PresetManager::getPreset(presetName);
    if (!presetSettings.templateName.isEmpty()) {
        setSettings(presetSettings);
        onSettingsChanged();
        
        // 保存用户选择的预设方案作为下次启动的默认选择
        ConfigManager::setDefaultPreset(presetName);
        ConfigManager::sync();
    }
}

void SettingsWidget::onPageNumberFormatChanged()
{
    QString format;

    if (m_pageNumberFormatCombo->currentText() == "自定义...") {
        format = m_pageNumberFormatEdit->text();
        m_pageNumberFormatEdit->setEnabled(true);
    } else {
        format = m_pageNumberFormatCombo->currentText();
        m_pageNumberFormatEdit->setEnabled(false);
        m_pageNumberFormatEdit->clear();
    }

    // 实时显示格式预览
    if (format.isEmpty()) {
        format = "{page}";
    }

    ProcessingSettings::PageNumberSettings tempSettings;
    tempSettings.format = format;
    QString preview = QString("示例: %1").arg(tempSettings.getFormatPreview(3, 15));
    m_formatPreviewLabel->setText(preview);

    onSettingsChanged();
}

void SettingsWidget::onMarginChanged()
{
    updateContentAreaInfo();

    // 移除所有直接UI更新，只通过单一信源更新
    onSettingsChanged();
}

void SettingsWidget::onDPIChanged()
{
    updateFileEstimate();
    onSettingsChanged();
}

void SettingsWidget::notifySettingsChanged()
{
    m_currentSettings = collectCurrentSettings();


    // 单一信源：只发射信号，所有UI更新都由MainWindow统一处理
    emit settingsChanged(m_currentSettings);
}

void SettingsWidget::updateContentAreaInfo()
{
    double totalVertical = m_topMarginSpin->value() + m_bottomMarginSpin->value();
    double totalHorizontal = m_leftMarginSpin->value() + m_rightMarginSpin->value();

    double contentWidth = 210.0 - totalHorizontal;   // A4宽度210mm
    double contentHeight = 297.0 - totalVertical;    // A4高度297mm

    QString contentInfo = QString("%1×%2mm")
                         .arg(contentWidth, 0, 'f', 1)
                         .arg(contentHeight, 0, 'f', 1);

    if (contentWidth < 100 || contentHeight < 150) {
        contentInfo += " ⚠️";
        m_contentAreaLabel->setStyleSheet("color: red;");
    } else {
        m_contentAreaLabel->setStyleSheet("color: black;");
    }

    m_contentAreaLabel->setText(contentInfo);
}

void SettingsWidget::updateFileEstimate()
{
    ProcessingSettings tempSettings = collectCurrentSettings();

    // 获取当前文件的实际总页数
    int totalPages = getTotalPages();

    if (totalPages > 0) {
        QString estimate = tempSettings.getEstimatedFileSize(totalPages);
        m_fileSizeLabel->setText(estimate);
    } else {
        // 如果没有文件加载，显示默认信息
        QString estimate = tempSettings.getEstimatedFileSize(1);
        m_fileSizeLabel->setText(QString("%1 (无文件)").arg(estimate));
    }
}

ProcessingSettings SettingsWidget::collectCurrentSettings() const
{
    ProcessingSettings settings;

    // DPI设置 - 直接获取数值
    settings.standardDPI = m_dpiCombo->currentText().toInt();
    settings.autoOptimizeLargeDocuments = m_autoOptimizeCheck->isChecked();

    // 页边距
    settings.margins.top = m_topMarginSpin->value();
    settings.margins.bottom = m_bottomMarginSpin->value();
    settings.margins.left = m_leftMarginSpin->value();
    settings.margins.right = m_rightMarginSpin->value();

    // 页码设置 - Jony Ive风格扩展
    settings.pageNumber.enabled = m_pageNumberEnabled->isChecked();
    settings.pageNumber.startNumber = m_startNumberSpin->value();

    // 页码格式
    if (m_pageNumberFormatCombo->currentText() == "自定义...") {
        settings.pageNumber.format = m_pageNumberFormatEdit->text();
    } else {
        settings.pageNumber.format = m_pageNumberFormatCombo->currentText();
    }

    if (settings.pageNumber.format.isEmpty()) {
        settings.pageNumber.format = "{page}";
    }

    // === 页码属性收集 - 优先使用UI设置，然后合并SmartSelector的位置和网格状态 ===
    if (m_smartSelector) {
        // 获取SmartSelector的位置和网格状态
        ProcessingSettings::PageNumberSettings smartSettings = m_smartSelector->getPageNumberSettings();
        settings.pageNumber.position = smartSettings.position;
        settings.pageNumber.gridState = smartSettings.gridState;
    }

    // 字体设置覆盖
    if (m_fontFamilyCombo) {
        settings.pageNumber.font.setFamily(m_fontFamilyCombo->currentText());
    }

    if (m_fontSizeCombo) {
        settings.pageNumber.font.setPointSize(m_fontSizeCombo->currentData().toInt());
    }

    if (m_fontBoldButton) {
        settings.pageNumber.font.setBold(m_fontBoldButton->isChecked());
    }

    if (m_fontItalicButton) {
        settings.pageNumber.font.setItalic(m_fontItalicButton->isChecked());
    }

    // 页码颜色设置
    if (m_smartSelector) {
        ProcessingSettings::PageNumberSettings smartSettings = m_smartSelector->getPageNumberSettings();
        settings.pageNumber.color = smartSettings.color;
    }

    // 精准定位滑块已移除 - 现在使用直接拖拽定位

    // 模板名称
    settings.templateName = m_presetCombo->currentText();

    return settings;
}

QIcon SettingsWidget::createInfoIcon() const
{
    QPixmap pixmap(16, 16);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制信息图标（圆形内带i）
    painter.setPen(QPen(QColor(70, 130, 180), 1.5));
    painter.setBrush(QColor(173, 216, 230));

    // 外圆
    painter.drawEllipse(2, 2, 12, 12);

    // 绘制字母i
    painter.setPen(QPen(QColor(70, 130, 180), 2));
    painter.setFont(QFont("Arial", 8, QFont::Bold));
    painter.drawText(QRect(2, 2, 12, 12), Qt::AlignCenter, "i");

    return QIcon(pixmap);
}

int SettingsWidget::getTotalPages() const
{
    if (!m_mainWindow) {
        return 0;
    }

    // Martin Fowler重构：统一使用全局总页数，确保所有UI组件显示一致
    // 用户要求所有组件都显示相同的总页数（与状态栏保持一致）
    if (PageView* pageView = m_mainWindow->getPageView()) {
        return pageView->getGlobalTotalPageCount();
    }

    return 0;
}

void SettingsWidget::onFileListChanged()
{
    // 文件列表变化时更新文件大小预估
    updateFileEstimate();
}

void SettingsWidget::onPageCountChanged()
{
    // 页数变化时更新文件大小预估
    updateFileEstimate();

    // 更新SmartPageNumberSelector的总页数
    updateSmartSelectorPageInfo();
}

void SettingsWidget::onCurrentPageChanged()
{
    // 当前页变化时更新SmartPageNumberSelector
    updateSmartSelectorPageInfo();
}

void SettingsWidget::updateSmartSelectorPageInfo()
{
    if (!m_smartSelector || !m_mainWindow) {
        return;
    }

    // 获取总页数
    int totalPages = getTotalPages();

    // 获取当前页码（使用全局页码）
    int currentPage = 1; // 默认第1页
    if (PageView* pageView = m_mainWindow->getPageView()) {
        currentPage = qMax(1, pageView->getCurrentPageNumber()); // 使用全局页码而不是本地页码
    }


    // 更新SmartPageNumberSelector
    m_smartSelector->setSamplePage(currentPage, qMax(1, totalPages));

}

void SettingsWidget::showMarginPresetMenu()
{
    QMenu* presetMenu = new QMenu(this);
    
    // 添加边距预设选项
    QStringList presetNames = ProcessingSettings::getMarginPresetNames();
    QList<ProcessingSettings::MarginPreset> presets = {
        ProcessingSettings::MarginPreset::Zero,
        ProcessingSettings::MarginPreset::Minimal,
        ProcessingSettings::MarginPreset::Narrow,
        ProcessingSettings::MarginPreset::Standard,
        ProcessingSettings::MarginPreset::Wide,
        ProcessingSettings::MarginPreset::Academic,
        ProcessingSettings::MarginPreset::Print
    };
    
    for (int i = 0; i < presetNames.size() && i < presets.size(); ++i) {
        const QString& name = presetNames[i];
        ProcessingSettings::MarginPreset preset = presets[i];
        
        QAction* action = presetMenu->addAction(name, [this, preset]() {
            applyMarginPreset(preset);
        });
        
        // 添加工具提示
        action->setToolTip(ProcessingSettings::getMarginPresetDescription(preset));
    }
    
    // 在按钮下方显示菜单
    QPoint globalPos = m_marginPresetButton->mapToGlobal(
        QPoint(0, m_marginPresetButton->height())
    );
    presetMenu->exec(globalPos);
    
    // 菜单会自动删除
    presetMenu->deleteLater();
}

void SettingsWidget::applyMarginPreset(ProcessingSettings::MarginPreset preset)
{
    ProcessingSettings::MarginSettings margins = ProcessingSettings::getMarginPreset(preset);
    
    // 更新UI控件
    m_topMarginSpin->setValue(margins.top);
    m_bottomMarginSpin->setValue(margins.bottom);
    m_leftMarginSpin->setValue(margins.left);
    m_rightMarginSpin->setValue(margins.right);
    
    // 更新内容区域信息
    updateContentAreaInfo();
    
    // 触发设置变更通知
    onSettingsChanged();
}

int SettingsWidget::extractDPIFromText(const QString& text) const
{
    // 使用正则表达式从描述文本中提取DPI数值
    QRegularExpression re(R"(DPI=(\d+))");
    QRegularExpressionMatch match = re.match(text);
    return match.hasMatch() ? match.captured(1).toInt() : 150; // 默认150 DPI
}

void SettingsWidget::updatePresetCombo()
{
    m_presetCombo->clear();
    
    // 添加所有8个预设
    QStringList allPresets = PresetManager::getAllPresetNames();
    m_presetCombo->addItems(allPresets);
}

void SettingsWidget::saveAsPreset()
{
    QString currentPresetName = m_presetCombo->currentText();
    
    if (!PresetManager::isUserPreset(currentPresetName)) {
        QMessageBox::information(this, "无法保存", "只能保存到\"我的预设\"槽位。");
        return;
    }
    
    ProcessingSettings currentSettings = collectCurrentSettings();
    currentSettings.templateName = currentPresetName;
    
    if (PresetManager::savePreset(currentPresetName, currentSettings)) {
        // 使用ToastNotification替代对话框
        ToastNotification::showSuccess(this, 
            QString("预设 '%1' 已保存成功！").arg(currentPresetName));
    } else {
        ToastNotification::showError(this, "无法保存预设。");
    }
}

// === 新增的一体化页码功能槽函数 ===

void SettingsWidget::onSmartPositionChanged(SmartPageNumberSelector::Position position)
{
    // 位置变更由智能选择器自动处理
    onSettingsChanged();
}

void SettingsWidget::onSmartSettingsChanged(const ProcessingSettings::PageNumberSettings& settings)
{
    // Martin Fowler重构：统一页码设置管理
    // 由于SmartPageNumberSelector不再直接触发settingsChanged信号
    // 这里需要统一管理所有页码设置变化
    
    // 智能选择器设置变更
    emit pageNumberPositionChanged(settings);

    // 统一触发设置变化，确保所有组件同步更新
    onSettingsChanged();
}

void SettingsWidget::onFontFamilyChanged()
{
    if (m_smartSelector) {
        ProcessingSettings::PageNumberSettings settings = m_smartSelector->getPageNumberSettings();
        settings.font.setFamily(m_fontFamilyCombo->currentText());
        m_smartSelector->setPageNumberSettings(settings);
    }
    onSettingsChanged();
}

void SettingsWidget::onFontSizeChanged()
{
    int fontSize = m_fontSizeCombo->currentData().toInt();
    if (m_smartSelector) {
        ProcessingSettings::PageNumberSettings settings = m_smartSelector->getPageNumberSettings();
        settings.font.setPointSize(fontSize);
        m_smartSelector->setPageNumberSettings(settings);
    }
    onSettingsChanged();
}

void SettingsWidget::onFontStyleChanged()
{
    if (m_smartSelector) {
        ProcessingSettings::PageNumberSettings settings = m_smartSelector->getPageNumberSettings();
        settings.font.setBold(m_fontBoldButton->isChecked());
        settings.font.setItalic(m_fontItalicButton->isChecked());
        m_smartSelector->setPageNumberSettings(settings);
    }
    onSettingsChanged();
}

void SettingsWidget::onFontColorChanged()
{
    QColor color = QColorDialog::getColor(Qt::black, this, "选择页码颜色");
    if (color.isValid()) {
        if (m_smartSelector) {
            ProcessingSettings::PageNumberSettings settings = m_smartSelector->getPageNumberSettings();
            settings.color = color;
            m_smartSelector->setPageNumberSettings(settings);
        }
        // 不再更新按钮背景色，保持与加粗、倾斜按钮一致的样式
    }
    onSettingsChanged();
}

// 精准定位槽函数已移除 - 现在使用直接拖拽定位

void SettingsWidget::resetPageNumberToDefaults()
{
    // 重置到默认值
    if (m_smartSelector) {
        ProcessingSettings::PageNumberSettings defaultSettings;
        m_smartSelector->setPageNumberSettings(defaultSettings);
    }

    // 重置UI控件
    m_pageNumberEnabled->setChecked(false);
    m_fontFamilyCombo->setCurrentText("SF Pro Display");
    m_fontSizeCombo->setCurrentText("12");
    m_fontBoldButton->setChecked(false);
    m_fontItalicButton->setChecked(false);
    // 精准定位滑块已移除 - 现在使用直接拖拽定位

    onSettingsChanged();
}
